package com.yidian.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yidian.dao.SkuMapper;
import com.yidian.dao.StockBackMapper;
import com.yidian.pojo.goods.StockBack;
import com.yidian.pojo.order.OrderItem;
import com.yidian.server.goods.StockBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author whb
 * @create 2021-09-06 10:40
 * @desciption 库存回滚Service服务接口实现类
 */
@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService {
    @Autowired
    private StockBackMapper stockBackMapper;
    @Autowired
    private SkuMapper skuMapper;

    /**
     * 添加库存回滚信息
     * @param orderItems
     */
    @Override
    @Transactional
    public void addStockBackList(List<OrderItem> orderItems) {
        for (OrderItem orderItem:orderItems){
            //构建库存回滚对象
            StockBack stockBack = new StockBack();
            stockBack.setOrderId(orderItem.getOrderId());//订单号
            stockBack.setSkuId(orderItem.getSkuId());//skuId
            stockBack.setStatus("0");//初始回滚状态为0
            stockBack.setNum(orderItem.getNum());//订单中某一商品的数量
            stockBack.setCreateTime(new Date());//回滚信息创建时间
            stockBackMapper.insert(stockBack);
        }
    }

    /**
     * 执行库存回滚
     */
    @Override
    public void doBack() {
        //构建状态为0的库存回滚实体类对象
        StockBack stockBack = new StockBack();
        stockBack.setStatus("0");
        //查询需要库存回滚的集合
        List<StockBack> stockBackList = stockBackMapper.select(stockBack);

        //编写库存回滚逻辑
        for (StockBack stockBackIng:stockBackList){
            skuMapper.deductionStock(stockBackIng.getSkuId(),-stockBackIng.getNum());//增加库存
            skuMapper.addSaleNum(stockBackIng.getSkuId(),-stockBackIng.getNum());//减少销量
            stockBack.setStatus("1");//改变库存回滚状态，0：位回滚 1：已回滚
            stockBack.setBackTime(new Date());//设置库存回滚时间
            stockBackMapper.updateByPrimaryKey(stockBack);//更新库存表中的信息
        }
    }
}
